//
//  TSBaseViewController.swift
//  TSProfitProject
//
//  Created by TmmmS on 2019/10/21.
//  Copyright © 2019 TMS. All rights reserved.
//

import UIKit
import SnapKit

class TSBaseViewController: UIViewController {
    
    let buttonH = 16
    var customBtn : UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = WHITE_COLOR
        
        if navigationController?.viewControllers.count ?? 0 >= 2 {
            createBackItem()
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if #available(iOS 13, *) {
            UIApplication.shared.statusBarStyle = .darkContent
        }  else {
            UIApplication.shared.statusBarStyle = .default
        }
    }
    
    func setupNavigationTitle(title:String) {
        
        customBtn.setTitle(title, for: .normal)
        
        var rect = customBtn.frame
        rect.size.width = calculateButtonWidth(title: title)
        customBtn.frame = rect
    }
    
    func calculateButtonWidth(title:String) -> CGFloat {
        
        let initialWidth : CGFloat = 14 + 15
        let titleW = NSString(string: title).boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: 15), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font:UIFont.systemFont(ofSize: 14, weight: .medium)], context: nil).size.width
        return initialWidth + titleW
    }

    deinit {
        TSLog("deinit: \(type(of: self))")
    }
}

// MARK: - CustomNavigationBar
extension TSBaseViewController {
    
    func createBackItem() {
        
        customBtn = UIButton.init(type: .custom)
        customBtn.frame = CGRect(x: 0, y: 0, width: 30, height: 16)
//        customBtn.backgroundColor = WHITE_COLOR
        customBtn.setTitleColor(UIColor.hexadecimalColor(hexadecimal: "#282828"), for: .normal)
        customBtn.setImage(UIImage(named: "general_navigation_back"), for: .normal)
        customBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        customBtn.imageEdgeInsets = UIEdgeInsets(top: 0, left: -15, bottom: 0, right: 0)
        customBtn.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)
        customBtn.addTarget(self, action: #selector(backAction), for: .touchUpInside)
        
        let leftItem = UIBarButtonItem.init(customView: customBtn)
        
        navigationItem.leftBarButtonItem = leftItem
        
    }
    
    @objc private func backAction() {
        self.navigationController?.popViewController(animated: true)
    }
    
}
